package sketch.experiment;

import java.io.File;
import java.io.IOException;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FileASTRequestor;

import randoop.util.Files;
import sketch.util.Checker;
import sketch.util.Globals;
import sketch.util.SketchUtil;

public class EclipseIndependentASTReader {
	
	public static CompilationUnit readASTRoot(String fileName) throws IOException {
		File f = new File(fileName);
		Checker.checkTrue(f.exists() && f.isFile(), "The file is either not exisited or not a file: " + fileName);
		
		int lastPathSep = fileName.lastIndexOf(Globals.pathSep);
		String fileDir = ".";
		if(lastPathSep != -1) {
			fileDir = fileName.substring(0, lastPathSep);
		}
		File parent = new File(fileDir);
		//create the parser
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		
		//Globals.getClasspath()
		parser.setSource(Files.getFileContents(fileName).toCharArray());
		parser.setEnvironment(SketchUtil.getClassPathEntries(), new String[]{parent.getAbsolutePath()}, null, true);
		parser.setResolveBindings(true);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		
//		return (CompilationUnit)parser.createAST(null);
		
		final CompilationUnit returnNode = null;
		parser.createASTs(new String[]{fileName}, null, new String[0], 
				new FileASTRequestor() {
			        public void acceptAST(String sourcePath, CompilationUnit ast) {
			        	//System.out.println("FILE: " + sourcePath + ", its ast is: \n" + ast.toString());
			        	StoreNode.storeCompilationUnit(ast);
			        }
		        }
				, null);
		return StoreNode.stored;
	}
	
	static class StoreNode {
		static CompilationUnit stored = null;
		static void storeCompilationUnit(CompilationUnit unit) {
			stored = unit;
		}
	}
	
	public static void main(String[] args) throws IOException {
	   String filePath = "./tmp/TestSketchExamples.java"; 
	   if(args.length != 0) {
		   filePath = args[0];
	   }
	   CompilationUnit unit = readASTRoot(filePath);
	   System.out.println("unit: " + unit);
	}
	
}